package com.zoro.dyformservice.support.response;

import com.zoro.dyformservice.constants.response.ResponseStatus;
import jakarta.annotation.Nonnull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zhaoxingwu
 */
public class CommonResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    public CommonResponseBodyAdvice() {
    }

    @Override
    public boolean supports(@Nonnull MethodParameter returnType,
                            @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnType.getMethod() == null) {
            return false;
        }
        return MappingJackson2HttpMessageConverter.class == converterType
                && !ResponseEntity.class.isAssignableFrom(returnType.getMethod().getReturnType())
                && !org.springframework.http.ResponseEntity.class.isAssignableFrom(returnType.getMethod().getReturnType());
    }

    @Override
    public Object beforeBodyWrite(Object body, @Nonnull MethodParameter returnType,
                                  @Nonnull MediaType selectedContentType,
                                  @Nonnull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @Nonnull ServerHttpRequest request,
                                  @Nonnull ServerHttpResponse response) {
        if (body instanceof ResponseEntity<?>) {
            return body;
        }

        if (selectedContentType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)) {
            ResponseEntity<Object> res = new ResponseEntity<>(ResponseStatus.OK);
            res.setData(body);
            // TODO 这里还是需要分页信息
            return res;
        } else {
            return body;
        }
    }
}
